package com.voice.server.publish.device;

import com.alibaba.fastjson.JSONObject;
import com.voice.core.DefaultClient;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.utils.ResponseUtil;
import com.voice.server.connection.DeviceControllerConnection;
import com.voice.server.entity.DevicePinYinCode;
import com.voice.server.map.PinYinCodeMap;
import com.voice.server.publish.PublishHandler;
import com.voice.server.repository.DevicePinYinCodeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component("/device/pub/pinyin/code")
@Transactional
public class PinYinCodeHandler implements PublishHandler<DeviceControllerConnection> {

    @Autowired
    private DevicePinYinCodeRepository devicePinYinCodeRepository;
    @Autowired
    private DefaultClient defaultClient;
    @Autowired
    private PinYinCodeMap pinYinCodeMap;

    @Override
    public void handle(Stream stream,StreamData streamData, DeviceControllerConnection connection){
        JSONObject jsonObject=JSONObject.parseObject(new String(streamData.readAllData()));
        if(jsonObject==null) return;
        String pinYin=jsonObject.getString("pinyin");
        int code=jsonObject.getIntValue("code");
        DevicePinYinCode devicePinYinCode=devicePinYinCodeRepository.findByDeviceKeyAndCode(connection.getDeviceKey(),code);
        if(devicePinYinCode==null) {
            devicePinYinCode=new DevicePinYinCode();
            devicePinYinCode.setDeviceKey(connection.getDeviceKey());
            devicePinYinCode.setPinyin(pinYin);
            devicePinYinCode.setCode(code);
            pinYinCodeMap.add(devicePinYinCode);
        }else {
            devicePinYinCode.setPinyin(pinYin);
            pinYinCodeMap.update(devicePinYinCode,code);
        }
        devicePinYinCodeRepository.save(devicePinYinCode);
        this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.success());
    }
}
